package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Vetting;
import com.example.educationalsystem.entity.Vo.CourseVo;
import com.example.educationalsystem.entity.Vo.VoteVo;
import com.example.educationalsystem.entity.Vo.VoteVo;
import com.example.educationalsystem.entity.Vote;
import com.example.educationalsystem.service.IVoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/vote",tags="得票信息管理")
@RestController
@RequestMapping("/vote")
public class VoteController {
    @Autowired
    private IVoteService iVoteService;
    @GetMapping("/getVotePage")
    @ApiOperation(value = "获取得票分页信息",notes = "获取选课得票信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getVotePage(
            @RequestParam(value = "size", defaultValue = "10") long size,
            @RequestParam(value = "current", defaultValue = "1") long current,
            String studentId,String courseId
    )
    {
        ResponseJson responseJson=new ResponseJson();
        Page<VoteVo> page=new Page<>(current,size);
        QueryWrapper<VoteVo> queryWrapper=new QueryWrapper<>();
        if(studentId==null&&courseId==null)
        {
            queryWrapper=null;
        }

        Page<VoteVo> VoteVoPage=iVoteService.getVotePage(page,queryWrapper);
        if(VoteVoPage!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(VoteVoPage);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @GetMapping("/getAllVote")
    @ApiOperation(value = "获取所有得票信息",notes = "获取所有得票信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllVote()
    {
        ResponseJson responseJson=new ResponseJson();
        List<VoteVo> votelist=iVoteService.getAllVote();
        if(votelist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(votelist);
            
        }
        else
        {
           responseJson.setStatus(404);
           responseJson.setMsg("查询为空，无得票信息！");
        }
        return responseJson;
    }
    @ApiOperation(value = "导出所有得票信息",notes = "导出所有得票信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            EasyExcel.write(response.getOutputStream(), VoteVo.class).sheet(tableName).doWrite(iVoteService.getAllVote());
        }catch(Exception e)
        {
            response.reset();
        }


    }
    @ApiOperation(value = "导入得票信息",notes = "导入得票信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, VoteVo.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() >=1) {
                for (int i = 0; i < list.size(); i++) {
                    Vote vote= (Vote) list.get(i);
                    //使用mybatis-plus添加到数据库
                    iVoteService.save(vote);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }

    @ApiOperation(value = "增加得票信息",notes = "增加一条得票信息记录")
    @PostMapping("/insertVote")
    @ResponseBody
    public ResponseJson insertVote(@RequestBody Vote requestVote)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vote> queryWrapper=new QueryWrapper<>();
        Vote voteOne=iVoteService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",requestVote.getTeacherId()));
        if(voteOne==null)
        {
            Boolean result=iVoteService.save(requestVote);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestVote);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该记录已存在！");
        }
        return responseJson;
    }

    @ApiOperation(value = "批量删除得票信息",notes = "根据得票编号，删除多条得票信息")
    @DeleteMapping("/deleteVotes")
    @ResponseBody
    public  ResponseJson deleteVotes( @ApiParam(name = "Ids", value = "得票IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iVoteService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "删除得票信息",notes = "根据教师ID，删除一条得票信息")
    @DeleteMapping("/deleteVote")
    @ResponseBody
    public  ResponseJson deleteVote( @ApiParam(name = "teacherId", value = "教师编号", required = true) @RequestParam String teacherId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vote> queryWrapper=new QueryWrapper<>();
        Vote voteOne=iVoteService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",teacherId));
        if(voteOne!=null)
        {
            int result=iVoteService.getBaseMapper().deleteById(voteOne.getVoteId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(voteOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("得票信息不存在！");
        }
        return responseJson;

    }
    
    @ApiOperation(value = "更新得票信息",notes = "更新得票信息，必须填写教师ID")
    @PutMapping("/updateVote")
    @ResponseBody
    public ResponseJson updateVote(@RequestBody  Vote resquestVote)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vote> queryWrapper=new QueryWrapper<>();
        Vote voteOne=iVoteService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",resquestVote.getTeacherId()));
        if(voteOne!=null)
        {
            QueryWrapper<Vote> queryWrapper1=new QueryWrapper<>();
            int result=iVoteService.getBaseMapper().update(resquestVote,queryWrapper1.eq("teacher_id",resquestVote.getTeacherId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestVote);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("得票信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

